<template>
  <div class="ingredient-management">
    <!-- 查询栏 -->
    <QueryBar @query="handleQuery" />
    <GenericManagement
      :dataList="ingredientList"
      :columns="columns"
      :formFields="formFields"
      @add="handleAddFood"
      @edit="handleEditFood"
      @delete="handleDeleteFood"
      primaryKey="food_id"
      entityName="食材"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import GenericManagement from '../components/GenericManagement.vue';
import QueryBar from '../components/QueryBar.vue';
import axios from 'axios';

const ingredientList = ref([]);
const currentQueryId = ref(null); // 当前查询的ID

// 表格列配置（与实验指导书要求一致）
const columns = [
  { prop: 'food_id', label: 'ID', width: '100' },
  { prop: 'food_name', label: '名称', width: '120' },
  { prop: 'category', label: '分类', width: '120' },
  { prop: 'calories', label: '热量 (kcal)', width: '120' },
  { prop: 'protein', label: '蛋白质 (g)', width: '120' },
  { prop: 'fat', label: '脂肪 (g)', width: '120' },
  { prop: 'carbohydrate', label: '碳水化合物 (g)', width: '120' }
];

// 表单字段配置（与实验指导书要求一致）
const formFields = [
  { prop: 'food_id', label: '食物 ID', type: 'input' },
  { prop: 'food_name', label: '名称', type: 'input' },
  {
    prop: 'category',
    label: '分类',
    type: 'select',
    options: [
      { label: '蛋类', value: '蛋类' },
      { label: '蔬菜', value: '蔬菜' },
      { label: '谷物', value: '谷物' }
    ]
  },
  { prop: 'calories', label: '热量 (kcal)', type: 'input' },
  { prop: 'protein', label: '蛋白质 (g)', type: 'input' },
  { prop: 'fat', label: '脂肪 (g)', type: 'input' },
  { prop: 'carbohydrate', label: '碳水化合物 (g)', type: 'input' }
];

// 获取全部食物列表（修正函数名：将fetchAllData改为fetchFoodList）
const fetchFoodList = async () => {
  try {
    const response = await axios.get('http://localhost:8080/DietManagementSystem_war/admin/food/list');
    ingredientList.value = response.data || []; // 处理空数据
  } catch (error) {
    console.error('获取数据时出错:', error);
  }
};

// 按ID查询数据
const fetchById = async (id) => {
  if (id) {
    try {
      const response = await axios.get(`http://localhost:8080/DietManagementSystem_war/admin/food/${id}`);
      ingredientList.value = response.data ? [response.data] : []; // 单条数据转为数组
    } catch (error) {
      console.error('查询失败:', error);
      ingredientList.value = [];
    }
  } else {
    await fetchFoodList(); // 调用正确的函数名
  }
};

// 处理查询事件（新增handleQuery函数）
const handleQuery = (id) => {
  currentQueryId.value = id; // 更新查询ID
};

// 监听查询ID变化（初始化时加载全部数据）
watch(currentQueryId, async (newId) => {
  await fetchById(newId);
}, { immediate: true });

// 添加食物
const handleAddFood = async (food) => {
  try {
    await axios.post('http://localhost:8080/DietManagementSystem_war/admin/food/add', food);
    await fetchFoodList(); // 调用正确的函数名
  } catch (error) {
    console.error('添加数据时出错:', error);
  }
};

// 编辑食物
const handleEditFood = async (food) => {
  try {
    await axios.put('http://localhost:8080/DietManagementSystem_war/admin/food/update', food);
    await fetchFoodList(); // 调用正确的函数名
  } catch (error) {
    console.error('更新数据时出错:', error);
  }
};

// 删除食物
const handleDeleteFood = async (id) => {
  try {
    await axios.delete(`http://localhost:8080/DietManagementSystem_war/admin/food/delete/${id}`);
    await fetchFoodList(); // 调用正确的函数名
  } catch (error) {
    console.error('删除数据时出错:', error);
  }
};

// 初始化加载数据（调用正确的函数名）
fetchFoodList();
</script>

<style scoped>
.ingredient-management {
  padding: 20px;
}
</style>